<template>
  <div class="accompanying-management">
    <!-- 卡片容器：统一管理页面内容 -->
    <el-card class="box-card">
      <!-- 搜索条件区域：多条件筛选 -->
      <el-form 
        :inline="true" 
        :model="searchForm" 
        class="search-form"
        size="mini"
      >
        <el-form-item label="用户ID">
          <el-input 
            v-model="searchForm.id" 
            placeholder="请输入ID" 
            clearable
            style="width: 120px"
          ></el-input>
        </el-form-item>

        <el-form-item label="陪玩昵称">
          <el-input 
            v-model="searchForm.nickname" 
            placeholder="请输入昵称" 
            clearable
            style="width: 160px"
          ></el-input>
        </el-form-item>

        <el-form-item label="余额范围">
          <el-input-number 
            v-model="searchForm.minMoney" 
            placeholder="最小" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
          <span class="range-separator">-</span>
          <el-input-number 
            v-model="searchForm.maxMoney" 
            placeholder="最大" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="游戏状态">
          <el-select 
            v-model="searchForm.playmateStatus" 
            placeholder="请选择" 
            clearable
            style="width: 140px"
          >
            <el-option label="空闲" value="0"></el-option>
            <el-option label="游戏中" value="1"></el-option>
            <el-option label="下线" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址">
          <el-select 
            v-model="searchForm.addressName" 
            placeholder="请选择" 
            clearable
            style="width: 160px"
          >
            <el-option 
              v-for="item in addressList" 
              :key="item.id" 
              :label="item.addressName" 
              :value="item.addressName"
            ></el-option>
            <el-option v-if="!addressList.length" value="" disabled>暂无地址数据</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="游戏时长(小时)">
          <el-input-number 
            v-model="searchForm.minGameTime" 
            placeholder="最小" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
          <span class="range-separator">-</span>
          <el-input-number 
            v-model="searchForm.maxGameTime" 
            placeholder="最大" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
        </el-form-item>

        <el-form-item class="search-btns">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 陪玩列表表格：展示核心信息 + 状态 -->
      <el-table 
        :data="playmateList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        size="mini"
      >
        <el-table-column sortable prop="id" label="用户ID" width="80" align="center"></el-table-column>
        <el-table-column sortable prop="playmateNickname" label="陪玩昵称" align="center"></el-table-column>
        <el-table-column sortable prop="playmateName" label="真实姓名" align="center"></el-table-column>
        <el-table-column sortable prop="addressName" label="地址" align="center"></el-table-column>
        <el-table-column sortable prop="playmateMoney" label="账户余额" align="center">
          <template slot-scope="scope">{{ scope.row.playmateMoney ? scope.row.playmateMoney.toFixed(2) : '0.00' }}</template>
        </el-table-column>
        <el-table-column sortable prop="playmateGameTime" label="游戏时长(小时)" align="center">
          <template slot-scope="scope">{{ scope.row.playmateGameTime || 0 }}</template>
        </el-table-column>
        <el-table-column sortable prop="playmateGameStatus" label="游戏状态" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.playmateGameStatus)" 
              size="mini"
            >
              {{ getGameStatusText(scope.row.playmateGameStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userStatus" label="禁用状态" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getUserStatusTagType(scope.row.userStatus)" 
              size="mini"
            >
              {{ getUserStatusText(scope.row.userStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column sortable prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleViewDetail(scope.row)"
            >
              查看详情
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleChangeStatus(scope.row)"
              :icon="scope.row.userStatus === 0 ? 'el-icon-lock' : 'el-icon-unlock'"
              :class="scope.row.userStatus === 0 ? 'lock-btn' : 'unlock-btn'"
            >
              {{ scope.row.userStatus === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件：适配多数据量场景 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
        size="mini"
      ></el-pagination>
    </el-card>

    <!-- 状态修改弹窗：仅含核心字段 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="40%"
      center
      size="mini"
    >
      <el-form 
        :model="editForm" 
        label-width="120px" 
        ref="editFormRef"
        :rules="formRules"
        size="mini"
      >
        <el-form-item label="用户ID" v-if="editForm.id">
          <el-input v-model="editForm.id" disabled placeholder="无"></el-input>
        </el-form-item>

        <el-form-item label="禁用状态" prop="userStatus">
          <el-select 
            v-model="editForm.userStatus" 
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveStatus" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog 
      title="陪玩详情" 
      :visible.sync="detailVisible" 
      width="60%"
      destroy-on-close
    >
      <el-row :gutter="20">
        <!-- 基本信息区域 -->
        <el-col :span="24">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="陪玩姓名">{{ detailData.playmateName }}</el-descriptions-item>
            <el-descriptions-item label="陪玩昵称">{{ detailData.playmateNickname }}</el-descriptions-item>
            <el-descriptions-item label="头像">
              <img 
                v-if="detailData.playmateAvatar" 
                :src="detailData.playmateAvatar" 
                style="width:60px;height:60px;border-radius:50%"
              >
              <span v-else>无头像</span>
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ detailData.playmateSex === 0 ? '女' : '男' }}
            </el-descriptions-item>
            <el-descriptions-item label="自我介绍">{{ detailData.playmateDesc }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ detailData.playmateEmail }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 游戏相关信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>游戏相关信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="游戏爱好">{{ detailData.playmateGameHobby }}</el-descriptions-item>
            <el-descriptions-item label="游戏时长">{{ detailData.playmateGameTime }} 小时</el-descriptions-item>
            <el-descriptions-item label="游戏状态">
              <el-tag 
                :type="detailData.playmateGameStatus === 0 ? 'success' : 
                       detailData.playmateGameStatus === 1 ? 'warning' : 'info'"
              >
                {{ detailData.playmateGameStatus === 0 ? '空闲' : 
                   detailData.playmateGameStatus === 1 ? '游戏中' : '下线' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="陪玩评分">{{ detailData.playmateRating }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 财务信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>财务信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="账户余额">{{ detailData.playmateMoney }} 元</el-descriptions-item>
            <el-descriptions-item label="保证金金额">{{ detailData.playmateMarginMoney }} 元</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 其他信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>其他信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="关联地址">{{ detailData.addressName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(detailData.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">{{ formatTime(detailData.updateTime) }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// 引入接口请求文件（需根据实际项目路径调整）
import adminApi from '@/http/adminApi.js';

export default {
  name: 'AccompanyingManagement',
  data() {
    return {
      // 地址列表：用于搜索条件的地址下拉框
      addressList: [],
      // 搜索表单数据：与后端查询接口参数对齐
      searchForm: {
        id: '',          // 用户ID
        nickname: '',    // 陪玩昵称
        minMoney: null,  // 余额最小值
        maxMoney: null,  // 余额最大值
        playmateStatus: '', // 游戏状态
        addressName: '', // 地址名称
        minGameTime: null, // 游戏时长最小值（小时）
        maxGameTime: null  // 游戏时长最大值（小时）
      },
      // 列表数据：存储查询到的陪玩用户信息
      playmateList: [],
      // 加载状态：控制表格加载动画
      loading: false,
      // 分页参数
      currentPage: 1,   // 当前页码
      pageSize: 10,     // 每页条数
      total: 0,         // 总数据量
      // 弹窗控制
      dialogVisible: false, // 弹窗显示/隐藏
      detailVisible: false, // 详情弹窗显示/隐藏
      dialogTitle: '',      // 弹窗标题（修改状态）
      // 状态修改表单
      editForm: {
        id: null,         // 用户ID（编辑时必传）
        userStatus: null // 禁用状态："启用" / "禁用"
      },
      // 详情数据
      detailData: {},
      // 表单验证规则
      formRules: {
        userStatus: [
          { required: true, message: '请选择禁用状态', trigger: 'change' }
        ]
      }
    };
  },
  // 页面挂载时加载初始化数据
  mounted() {
    this.initData();
  },
  methods: {
    /**
     * 初始化数据：先加载地址列表，再加载陪玩列表
     */
    async initData() {
      try {
        await this.fetchAddressList();
        await this.fetchPlaymateList();
      } catch (error) {
        this.$message.error('页面初始化失败，请刷新重试');
      }
    },

    /**
     * 获取地址列表：用于搜索条件的地址下拉框
     */
    async fetchAddressList() {
      this.loading = true;
      try {
        const res = await adminApi.getAddressList();
        if (res.code === 200) {
          this.addressList = res.data || [];
        } else {
          this.$message.error(res.message || '获取地址列表失败');
        }
      } catch (error) {
        this.$message.error('获取地址列表异常：' + error.message);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取陪玩用户列表：根据搜索条件和分页参数查询
     */
    async fetchPlaymateList() {
      this.loading = true;
      try {
        const reqParams = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        };
        const res = await adminApi.getAccompanyingUsers(reqParams);
        if (res.code === 200) {
          this.playmateList = res.data.list || [];
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取陪玩列表失败');
        }
      } catch (error) {
        this.$message.error('获取陪玩列表异常：' + error.message);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 搜索按钮点击：重置页码为1，重新查询
     */
    handleSearch() {
      this.currentPage = 1;
      this.fetchPlaymateList();
    },

    /**
     * 重置搜索表单：清空所有搜索条件，重新查询
     */
    resetSearch() {
      this.searchForm = {
        id: '',
        nickname: '',
        minMoney: '',
        maxMoney: '',
        playmateStatus: '',
        addressName: '',
        minGameTime: '',
        maxGameTime: ''
      };
      this.handleSearch();
    },

    /**
     * 每页条数改变：更新pageSize，重新查询
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchPlaymateList();
    },

    /**
     * 当前页码改变：更新currentPage，重新查询
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchPlaymateList();
    },

    /**
     * 查看详情按钮点击：获取并显示陪玩师详细信息
     */
    async handleViewDetail(row) {
      this.loading = true;
      try {
        const res = await adminApi.getAccompanyingUserDetail({ id: row.id });
        if (res.code === 200 && res.data) {
          this.detailData = res.data;
          this.detailVisible = true;
        } else {
          this.$message.error(res.message || '获取用户详情失败');
        }
      } catch (error) {
        this.$message.error('操作异常：' + (error.message || '查询用户详情失败'));
      } finally {
        this.loading = false;
      }
    },

    /**
     * 时间格式化：使用原生方法实现，不依赖外部format函数
     */
    formatTime(time) {
      if (!time) return '-';
      const date = new Date(time);
      // 处理无效日期
      if (isNaN(date.getTime())) return '-';
      
      // 补零函数
      const padZero = (num) => num.toString().padStart(2, '0');
      
      const year = date.getFullYear();
      const month = padZero(date.getMonth() + 1);
      const day = padZero(date.getDate());
      const hours = padZero(date.getHours());
      const minutes = padZero(date.getMinutes());
      const seconds = padZero(date.getSeconds());
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /**
     * 编辑按钮点击：回显当前用户状态，打开弹窗
     */
    async handleEdit(row) {
      this.dialogTitle = '修改用户状态';
      this.loading = true;
      try {
        const res = await adminApi.getAccompanyingUserDetail({ id: row.id });
        if (res.code === 200 && res.data) {
          const detail = res.data;
          this.editForm = {
            id: detail.id,
            // 数字转中文
            userStatus: detail.userStatus === 0 ? '启用' : '禁用',
            playmateNickname: detail.playmateNickname || '',
            playmateName: detail.playmateName || '',
            addressName: detail.addressName || '',
            playmateMoney: detail.playmateMoney || 0,
            playmateGameTime: detail.playmateGameTime || 0
          };
          this.dialogVisible = true;
        } else {
          this.$message.error(res.message || '获取用户详情失败，无法编辑');
        }
      } catch (error) {
        this.$message.error('操作异常：' + (error.message || '查询用户详情失败'));
      } finally {
        this.loading = false;
      }
    },

    /**
     * 保存状态：验证表单后调用后端接口
     */
    async saveStatus() {
      this.$refs.editFormRef.validate(async (isValid) => {
        if (!isValid) return;

        // 中文转数字
        const submitData = {
          ...this.editForm,
          userStatus: this.editForm.userStatus === '启用' ? 0 : 1
        };

        this.loading = true;
        try {
          const res = await adminApi.updateAccompanyingUser(submitData);
          if (res.code === 200) {
            this.$message.success(res.message || '操作成功');
            this.dialogVisible = false;
            this.fetchPlaymateList();
          } else {
            this.$message.error(res.message || '操作失败');
          }
        } catch (error) {
          this.$message.error('操作异常：' + error.message);
        } finally {
          this.loading = false;
        }
      });
    },

    /**
     * 删除用户：调用后端带绑定校验的删除接口
     */
    async handleDelete(row) {
      try {
        await this.$confirm(
          '确定删除该用户吗？\n提示：若该用户存在绑定的陪玩信息，将无法删除',
          '删除警告',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        this.loading = true;
        const res = await adminApi.deleteAccompanyingUser({ id: row.id });
        if (res.code === 200) {
          this.$message.success('删除成功'); 
          this.fetchPlaymateList();
        } else {
          this.$message.error(res.message || ' 删除失败：该用户存在绑定关系 '); 
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(' 删除异常：' + (error.message || ' 操作失败 '));
        }
      } finally {
        this.loading = false;
      }
    },

    /**
     * 游戏状态文字映射：数字转文字
     */
    getGameStatusText(status) {
      const statusMap = {
        0: '空闲',
        1: '游戏中',
        2: '下线'
      };
      return statusMap[status] || '未知状态';
    },

    /**
     * 游戏状态标签类型映射：匹配不同颜色
     */
    getStatusTagType(status) {
      const typeMap = {
        0: '',        // 默认灰色
        1: 'warning', // 游戏中-橙色
        2: 'info'     // 下线-蓝色
      };
      return typeMap[status] || '';
    },

    /**
     * 禁用状态文字映射：兼容数字和中文
     */
    getUserStatusText(status) {
      const statusMap = {
        '0': '启用',
        '1': '禁用',
        '启用': '启用',
        '禁用': '禁用'
      };
      return statusMap[status] || '未知状态';
    },

    /**
     * 禁用状态标签类型映射：匹配不同颜色
     */
    getUserStatusTagType(status) {
      const typeMap = {
        '0': 'success', // 启用-绿色
        '1': 'danger',  // 禁用-红色
        '启用': 'success',
        '禁用': 'danger'
      };
      return typeMap[status] || '';
    },

    // 状态切换方法
    async handleChangeStatus(row) {
      const newStatus = row.userStatus === 0 ? 1 : 0;
      const statusText = newStatus === 0 ? '启用' : '禁用';
      
      try {
        await this.$confirm(`确定要${statusText}该用户吗？`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const res = await adminApi.updateAccompanyingUser({
          id: row.id,
          userStatus: newStatus
        });
        
        if (res.code === 200) {
          this.$message.success(`${statusText}成功`);
          this.fetchPlaymateList();
        } else {
          this.$message.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作异常');
        }
      } finally {
        this.loading = false;
      }
    },
  }
};
</script>

<style scoped>
/* 卡片容器：增加阴影和圆角，优化内边距 */
.box-card {
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: none;
}

/* 搜索表单样式：优化背景和间距 */
.search-form {
  margin: 16px 20px;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

/* 范围选择分隔符：优化样式 */
.range-separator {
  margin: 0 8px;
  color: #86909c;
  font-size: 14px;
}

/* 搜索按钮组：调整间距 */
.search-btns {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

/* 表格样式：优化表头和行高 */
.el-table {
  border-radius: 6px;
  overflow: hidden;
}
.el-table__header-wrapper th {
  background-color: #f2f3f5;
  font-weight: 500;
  color: #1d2129;
  height: 44px;
}
.el-table__body-wrapper tr {
  height: 40px;
}
.el-table__body-wrapper tr:hover > td {
  background-color: #fafafa !important;
}

/* 状态标签：优化间距和样式 */
.el-tag {
  padding: 2px 8px;
  border-radius: 12px;
}

/* 分页样式：优化间距和对齐 */
.pagination {
  margin: 20px;
  text-align: right;
}

/* 操作按钮：优化颜色和 hover 效果 */
.el-button--text {
  color: #409eff;
  transition: color 0.2s;
}
.el-button--text:hover {
  color: #66b1ff;
}
.delete-btn {
  color: #f56c6c;
}
.delete-btn:hover {
  color: #f78989;
}

/* 弹窗样式：优化内边距和按钮组 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}
.el-dialog__body {
  padding: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 12px 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 8px 8px;
}

/* 表单项目：优化标签对齐 */
.el-form-item {
  margin-bottom: 0;
}
.el-form-item__label {
  font-weight: 400;
  color: #4e5969;
}

/* 输入框/选择器：优化样式 */
.el-input,
.el-select,
.el-input-number {
  border-radius: 4px;
  border-color: #dcdfe6;
  transition: border-color 0.2s, box-shadow 0.2s;
}
.el-input:focus-within,
.el-select:focus-within,
.el-input-number:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.lock-btn {
  color: #e6a23c;
}
.unlock-btn {
  color: #67c23a;
}
</style>